import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { CoreModule } from './core.module';

@Injectable({
    providedIn: CoreModule
})
export class MessageService {
    private subject = new Subject<any>();
    constructor(
    ) { }

    sendMessage(message: string, data?: any) {
        if (data) {
            this.subject.next({ text: message, data: data });
        } else {
            this.subject.next({ text: message });
        }
    }

    clearMessage() {
        if (this.subject.observers.length > 2) {
            for (let i = 0; i < this.subject.observers.length - 2; i++) {
                this.subject.observers.splice(i, 1);
            }
        }
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}